from dvadmin.utils.json_response import SuccessResponse, DetailResponse
from rest_framework.decorators import action
import pandas as pd

from dvadmin.utils.viewset import CustomModelViewSet

from se_admin.tables.DbaTables.serializers import DatabaseSerializer, DatabaseCreateUpdateSerializer, DatabaseImportSerializer, DatabaseExportSerializer
from se_admin.tables.DbaTables.serializers import DatabaseUserSerializer, DatabaseUserCreateUpdateSerializer, DatabaseUserImportSerializer, DatabaseUserExportSerializer
from se_admin.tables.DbaTables.serializers import TnsnameSerializer, TnsnameCreateUpdateSerializer, TnsnameImportSerializer, TnsnameExportSerializer
from se_admin.tables.DbaTables.serializers import DatabaseLinkSerializer, DatabaseLinkCreateUpdateSerializer, DatabaseLinkImportSerializer, DatabaseLinkExportSerializer


class DatabaseViewSet(CustomModelViewSet):
    """
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = DatabaseSerializer.Meta.model.objects.all()
    serializer_class = DatabaseSerializer
    create_serializer_class = DatabaseCreateUpdateSerializer
    update_serializer_class = DatabaseCreateUpdateSerializer

    filter_class = None

    export_field_label = {
        "host": "主机",
        "host_ip": "主机IP",
        "name": "实例",
        "env": "环境",
        "product": "产品",
        "edition": "Edition",
        "version": "Version",
        "release": "Release",
        "sid": "数据库",
        "ipaddress": "数据库IP",
        "port": "数据库端口",
        "log_model": "日志模式",
        "role": "角色",
        "characterset": "字符集",
        "encryption": "加密方式",
        "superuser": "DBA账户",
        "superpwd": "DBA密码",
        "status": "状态",
        "online_form": "上线表单",
        "offline_form": "下线表单",
        "update_datetime": "更新时间",
    }

    export_serializer_class = DatabaseExportSerializer

    import_field_dict = {
        "host": "主机",
        "host_ip": "主机IP",
        "name": "实例",
        "env": "环境",
        "product": "产品",
        "edition": "Edition",
        "version": "Version",
        "release": "Release",
        "sid": "数据库",
        "ipaddress": "数据库IP",
        "port": "数据库端口",
        "log_model": "日志模式",
        "role": "角色",
        "characterset": "字符集",
        "encryption": "加密方式",
        "superuser": "DBA账户",
        "superpwd": "DBA密码",
        "status": "状态",
        "online_form": "上线表单",
        "offline_form": "下线表单",
    }

    import_serializer_class = DatabaseImportSerializer

    # 注释编号:django-vue3-admin_views211216
    # 功能说明:被访问的model他要拿到外健的外键的值而进行重写懒加载请求，专门返回该字段外健的外键的值
    
    @action(methods=['post'], detail=False)
    def getbyIds(self, request, *args, **kwargs):

        # try:
        #     idList = request.data['values'] #获取前端传过来
        #     print(idList)
        # except:
        #      return DetailResponse(data=queryset, msg="没有传values到后端, 即是id列表")

        cur_model = self.get_queryset().model  #查到当前的model

        # queryset_id = cur_model.objects.filter(id__in=idList)  #过滤出来前端传过来的list列表里面的对象

        queryset_id = DatabaseSerializer.Meta.model.objects.all()

        queryset = list(queryset_id.values())

        try:
            fieldList = request.data['fieldList']

            df = pd.DataFrame(queryset, columns=fieldList)  #转换为pandas DataFrame格式，并且只拿其中列表内规定的字段
            print(df)

            newField =  fieldList[1].replace('_id', '') #把拿到的列表如['id', 'it_use_id']中的第二个元素fieldList[1]=it_use_id拿出来进行去除__id后缀

            try:
                #这里是拿到当前cur_model对应的newKey的外健对象的所有值并转为这字典
                choices_dict = dict(getattr(cur_model, newField).field.get_choices())
                #然后把对应的外健的值给组装回去df内
                df[f'{fieldList[1]}'] =  df[f'{fieldList[1]}'].replace(choices_dict)
            except AttributeError:
                #即是出现AttributeError: 'NoneType' object has no attribute 'model'错误时,不用理会
                pass
            queryset = df.to_dict(orient='records')  #pandas DataFrame转换成包含字典的列表格式

        except:
            pass

        return DetailResponse(data=queryset, msg="获取成功")
    # 注释编号:django-vue3-admin_views211216

class DatabaseUserViewSet(CustomModelViewSet):
    """
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = DatabaseUserSerializer.Meta.model.objects.all()
    serializer_class = DatabaseUserSerializer
    create_serializer_class = DatabaseUserCreateUpdateSerializer
    update_serializer_class = DatabaseUserCreateUpdateSerializer

    filter_class = None

    export_field_label = {
        "database": "所属数据库",
        "user": "用户名",
        "current_pwd": "当前密码",
        "in_use": "是否启用",
        "last_change": "上次改密时间",
        "last_pwd": "上次密码",
        "is_change": "是否改密",
        "next_pwd": "下次变更密码",
        "next_change": "下次改密时间",
        "create_form": "创建单号",
        "del_form": "删除单号",
        "update_datetime": "更新时间",
    }
    export_serializer_class = DatabaseUserExportSerializer

    import_field_dict = {
        "database": "所属数据库",
        "user": "用户名",
        "current_pwd": "当前密码",
        "in_use": "是否启用",
        "last_change": "上次改密时间",
        "last_pwd": "上次密码",
        "is_change": "是否改密",
        "next_pwd": "下次变更密码",
        "next_change": "下次改密时间",
        "create_form": "创建单号",
        "del_form": "删除单号",
    }
    import_serializer_class = DatabaseUserImportSerializer


class TnsnameViewSet(CustomModelViewSet):
    """
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = TnsnameSerializer.Meta.model.objects.all()
    serializer_class = TnsnameSerializer
    create_serializer_class = TnsnameCreateUpdateSerializer
    update_serializer_class = TnsnameCreateUpdateSerializer

    filter_class = None

    export_field_label = {
        "name": "TNS名称",
        "target_db": "目标数据库",
        "target_ip": "目标IP",
        "target_port": "目标端口",
        "host": "主机名",
        "host_ip": "主机IP",
        "status": "状态",
        "tns_full": "TNS全文",
        "update_datetime": "更新时间",
    }
    export_serializer_class = TnsnameExportSerializer

    import_field_dict = {
        "name": "TNS名称",
        "target_db": "目标数据库",
        "target_ip": "目标IP",
        "target_port": "目标端口",
        "host": "主机名",
        "host_ip": "主机IP",
        "status": "状态",
        "tns_full": "TNS全文",
    }
    import_serializer_class = TnsnameImportSerializer


class DatabaseLinkViewSet(CustomModelViewSet):
    """
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = DatabaseLinkSerializer.Meta.model.objects.all()
    serializer_class = DatabaseLinkSerializer
    create_serializer_class = DatabaseLinkCreateUpdateSerializer
    update_serializer_class = DatabaseLinkCreateUpdateSerializer

    filter_class = None

    export_field_label = {
        "name": "DB-Link Name",
        "owner": "Owner",
        "link_to": "目标数据库",
        "link_to_ip": "目标IP",
        "link_to_port": "目标端口",
        "link_type": "类型",
        "user_mapping": "目标用户",
        "database": "所属数据库",
        "status": "状态",
        "update_datetime": "更新时间",
    }
    export_serializer_class = DatabaseLinkExportSerializer

    import_field_dict = {

    }
    import_serializer_class = DatabaseLinkImportSerializer


